# -*- encoding:utf-8 -*-
# from __future__ import unicode_literals
import base64
from django.http import HttpResponse,Http404
from os import path
import os
from django.conf import settings
from Scanner import getAppRes
import re

import sys 
reload(sys) 
sys.setdefaultencoding('utf8') 


def proxy(request,path):
    """
    由于权限问题，需要代理网盘图片资源
    map url in global urls.py
    
    """
    path=base64.b64decode(path)
    path=path.decode('utf8')
    path = os.path.normpath(path)
    if not os.path.exists(path):
        raise Http404('resource not exist') 
    with open(path,'rb') as f:
        content=f.read()
    type=path.split('.')[-1]
    return HttpResponse(content,content_type='image/'+type)


class LogoSaver(object):
    def __init__(self,file,studio_name):
        self.file=file
        
        self.file_name='logo_{name}'.format(name=file.name)
        self.studio=studio_name
        self.msg=[]
    
    def is_valid(self):
        if self.file.name.lower().endswith(('.jpg','.png','.gif')):
            return True
        else:
            self.msg.append('file formate should be jpg,png,gif only')
            return False
    
    def save(self):
        file_path=self._get_path()
        with open(file_path,'wb') as f:
            for chunk in self.file.chunks():
                f.write(chunk)
                
    def _get_path(self):
        file_dir= path.join(settings.MEDIA_ROOT,self.studio)
        try:
            os.makedirs(file_dir)
        except os.error as e:
            pass 
        file_path = path.join(file_dir,self.file_name)
        return file_path
    
    def get_msg(self):
        return ';'.join(self.msg)
    def get_url(self):
        return '/media/{studio}/{file_name}'.format(studio=self.studio,file_name=self.file_name)

class FaviconSaver(LogoSaver):
    def __init__(self, file, studio_name):
        super(FaviconSaver,self).__init__(file, studio_name)
        self.file_name='favicon_{name}'.format(name=file.name)
        

def get_app_resource(media_url):
    #media_url=r'D:\work\relay\ALABS0003G - Coloring Book for Adults - Claming Dream Patterns\ALABS0003G - Coloring Book for Adults - Claming Dream Patterns'
    media_url=get_real_url(media_url)
    print('@'*20,media_url)
    res = getAppRes(media_url)
    icon =''
    fea_graph = ''
    screenshots = []
    if res.appIcon:
        icon='/proxy/'+base64.b64encode(res.appIcon.encode('utf8'))
    if res.featuredPic:
        fea_graph= '/proxy/'+base64.b64encode(res.featuredPic.encode('utf8'))
    if res.screenshots:
        screenshots= ['/proxy/'+base64.b64encode(s.encode('utf8')) for s in res.screenshots]
    dc={'icon':icon,
        'fea_graph':fea_graph,
        'screenshots': screenshots,
        'orientation':res.screenshotOrientation,   # portait   landscape
        }
    return dc



def get_real_url(media_url):
    """
    不同的服务器，media网盘地址不同
    """
    if not media_url:
        return ''
    root_path = settings.SUB_DOC
    ls = [r'^/Volumes/Project Submission Doc/(.*)',
          r'[A-Za-z]:(.*)',
          r'^\\\\[^\\]+\\[^\\]+(.*)']
    for pat in ls:
        mt = re.match(pat,media_url)
        if mt:
            break
    if mt:
        media_url=mt.group(1)
        media_url= media_url.replace('\\','/')
        media_url= media_url.lstrip('/') 
        media_url=os.path.join(root_path,media_url)
        return media_url
    else:
        return ''
    
    # if re.match(r'^/Volumes/Project Submission Doc/(.*)',media_url):
        # mt=re.match(r'^/Volumes',media_url)
    # elif re.match(r'[A-Za-z]:',media_url):
        # mt = re.match(r'[A-Za-z]:',media_url)
    # elif re.match(r'^\\\\[^\\]+\\[^\\]+',media_url):
        # mt = re.match(r'^\\\\[^\\]+\\[^\\]+',media_url)
    # else:
        # return ''
    # media_url=media_url.replace(mt.group(0),'',1)
    # media_url= media_url.replace('\\','/')
    # media_url= media_url.lstrip('/')
    # media_url=os.path.join(root_path,media_url)
    # return media_url


        